package xin.examinationSystem.servlet;

import com.alibaba.excel.EasyExcel;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

import xin.examinationSystem.account.Admin;
import xin.examinationSystem.account.Teacher;
import xin.examinationSystem.account.testPaper.excelTopic.*;
import xin.examinationSystem.utils.ExcelTools;


@WebServlet("/uploadExcel")
public class ExcelUploadServlet extends HttpServlet {

    public void init() {

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean adminStatus = false;
        boolean teacherStatus = false;
        Cookie[] cookies = request.getCookies();
        for (Cookie tCookie : cookies) {
            if (tCookie.getName().equals("accountMessage")) {
                HttpSession session = request.getSession();
                Admin attribute = (Admin) session.getAttribute(tCookie.getValue());
                if (attribute != null) {
                    adminStatus = true;
                }
            }
        }

        for (Cookie tCookie : cookies) {
            if (tCookie.getName().equals("accountMessageTeacher")) {
                HttpSession session = request.getSession();
                Teacher attribute = (Teacher) session.getAttribute(tCookie.getValue());
                if (attribute != null) {
                    teacherStatus = true;
                }
            }
        }


        if (!adminStatus && !teacherStatus) {
            response.sendRedirect("/index.html");
            return;
        }

        //判断是不是多段的数据(只有多段的数据,才是上传文件的)
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();

            //创建用于解析上传数据的工具类ServletFileUpLoad类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据,得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);

                TopicId topicId = TopicId.NULL;

                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        if (fileItem.getFieldName().equals("type")) {
                            switch (fileItem.getString("UTF-8")) {
                                case "A1":
                                    topicId = TopicId.SingleChoiceExcel;
                                    break;
                                case "A2":
                                    topicId = TopicId.MultipleChoiceQuestionExcel;
                                    break;
                                case "A3":
                                    topicId = TopicId.JudgeQuestionExcel;
                                    break;
                                case "A4":
                                    topicId = TopicId.GapFillingExcel;
                                    break;
                                case "A5":
                                    topicId = TopicId.EssayQuestionExcel;
                                    break;
                            }
                        }
                    }
                }

                if (topicId == TopicId.NULL) {
                    response.sendRedirect("/html/teacherSubpage/showImportNum.html?num=" + 0 + "#type=no");
                    return;
                }

                for (FileItem fileItem : list) {
                    //上传的是文件
                    if (!fileItem.isFormField()) {
                        //文件的绝对路径
                        String filePath = this.getServletConfig().getServletContext().getRealPath("/") + fileItem.getName();

                        if (filePath.equals(this.getServletConfig().getServletContext().getRealPath("/"))) {
                            response.sendRedirect("/html/teacherSubpage/showImportNum.html?num=" + 0 + "#type=no");
                            return;
                        }

                        //写入文件
                        fileItem.write(new File(filePath));

                        //false为符合标准,true为不符合标准
                        boolean status = false;

                        //读取文件
                        if (topicId == TopicId.SingleChoiceExcel) {
                            if (ExcelTools.judgeFormatIfCorrect(topicId, filePath)) {
                                EasyExcel.read(filePath, SingleChoiceExcel.class, new DataListener(new SingleChoiceExcel(), TopicId.SingleChoiceExcel)).sheet().doRead();
                            } else {
                                status = true;
                            }
                        } else if (topicId == TopicId.MultipleChoiceQuestionExcel) {
                            if (ExcelTools.judgeFormatIfCorrect(topicId, filePath)) {
                                EasyExcel.read(filePath, MultipleChoiceQuestionExcel.class, new DataListener(new MultipleChoiceQuestionExcel(), TopicId.MultipleChoiceQuestionExcel)).sheet().doRead();
                            } else {
                                status = true;
                            }
                        } else if (topicId == TopicId.JudgeQuestionExcel) {
                            if (ExcelTools.judgeFormatIfCorrect(topicId, filePath)) {
                                EasyExcel.read(filePath, JudgeQuestionExcel.class, new DataListener(new JudgeQuestionExcel(), TopicId.JudgeQuestionExcel)).sheet().doRead();
                            } else {
                                status = true;
                            }
                        } else if (topicId == TopicId.GapFillingExcel) {
                            if (ExcelTools.judgeFormatIfCorrect(topicId, filePath)) {
                                EasyExcel.read(filePath, GapFillingExcel.class, new DataListener(new GapFillingExcel(), TopicId.GapFillingExcel)).sheet().doRead();
                            } else {
                                status = true;
                            }
                        } else {
                            if (ExcelTools.judgeFormatIfCorrect(topicId, filePath)) {
                                EasyExcel.read(filePath, EssayQuestionExcel.class, new DataListener(new EssayQuestionExcel(), TopicId.EssayQuestionExcel)).sheet().doRead();
                            } else {
                                status = true;
                            }
                        }

                        if (status) {
                            if (topicId == TopicId.SingleChoiceExcel) {
                                System.out.println("文件A1格式错误!");
                            } else if (topicId == TopicId.MultipleChoiceQuestionExcel) {
                                System.out.println("文件A2格式错误!");
                            } else if (topicId == TopicId.JudgeQuestionExcel) {
                                System.out.println("文件A3格式错误!");
                            } else if (topicId == TopicId.GapFillingExcel) {
                                System.out.println("文件A4格式错误!");
                            } else {
                                System.out.println("文件A5格式错误!");
                            }
                            response.sendRedirect("/html/teacherSubpage/showImportNum.html?num=" + ExcelTools.excelNum(filePath) + "#type=no");
                            return;
                        }
                        response.sendRedirect("/html/teacherSubpage/showImportNum.html?num=" + ExcelTools.excelNum(filePath) + "#type=yes");
                        return;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void destroy() {
    }
}